/*
 * @Description:
 * @Author: menglong.du
 * @Date: 2021-11-17 15:26:33
 * @LastEditTime: 2022-01-09 15:11:41
 * @LastEditors: menglong.du
 */
import { defaultHeaders } from './defaultHeaders'

export function handleErrors(response) {
	if (!response.ok) {
		throw Error(response.statusText)
	}
	const contentType = response.headers.get('content-type')
	if (contentType && contentType.indexOf('application/json') !== -1) {
		return response.json()
	}
	if (contentType && contentType.indexOf('image/png') !== -1) {
		return response
	}
	if (contentType && contentType.indexOf('application/octet-stream') !== -1) {
		return response.blob()
	}
	return null
}

export function handleRetval(response) {
	if (response.message === 'SUCCESS' || response.status === 200) {
		return response
	}
	if (response.error) {
		return response
	}
	// todo: response.result which throwed need more beautify.
	if (response.result || response.message) {
		throw Error(response.result || response.message)
	} else {
		throw Error('Unknown error from server.')
	}
}

export function getApi(url, headers = defaultHeaders()) {
	const request = new Request(url, {
		method: 'GET',
		headers
	})
	return fetch(request).then(handleErrors)
}

export function postApi(url, body, headers = defaultHeaders()) {
	const request = new Request(url, {
		method: 'POST',
		headers,
		body
	})
	return fetch(request).then(handleErrors)
}

export function putApi(url, body = '', headers = defaultHeaders()) {
	const request = new Request(url, {
		method: 'PUT',
		headers,
		body
	})
	return fetch(request).then(handleErrors)
}

export function deleteApi(url, body, headers = defaultHeaders()) {
	const request = new Request(url, {
		method: 'DELETE',
		body,
		headers
	})
	return fetch(request).then(handleErrors)
	//.then(handleRetval);
}
